import { LoginStore } from './../store/login'
import { LocalCache } from '../utils/LocalCache'
import { diffTokenTime } from '../utils/auth'
import { ElMessage } from 'element-plus'

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

const instance: AxiosInstance = axios.create()

instance.defaults.baseURL = 'https://lianghj.top:8888/api/private/v1/'
instance.defaults.timeout = 6000

instance.interceptors.request.use((config: AxiosRequestConfig) => {
  if (diffTokenTime()) {
    const loginStore = LoginStore()
    // 在pinia中操作退出
    loginStore.timeoutlogin()
    ElMessage.error('token已过期')
  }
  if (config.headers) {
    config.headers.Authorization = LocalCache.getitem('token')
  }
  return config
})

instance.interceptors.response.use((data: AxiosResponse) => {
  return data.data
})

export { instance }
